from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from app.schemas.chat import Chat, ChatCreate, ChatUpdate
from app.schemas.message import Message, MessageCreate
from app.services.chat_service import create_chat, get_chat, get_user_chats, update_chat, delete_chat, get_chat_messages

router = APIRouter()

@router.post("/", response_model=Chat)
async def create_chat_endpoint(chat: ChatCreate):
    """创建新聊天"""
    try:
        new_chat = await create_chat(chat)
        return new_chat
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

@router.get("/{chat_id}", response_model=Chat)
async def read_chat(chat_id: str):
    """获取聊天详情"""
    chat = await get_chat(chat_id)
    if not chat:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Chat not found"
        )
    return chat

@router.get("/", response_model=List[Chat])
async def read_chats(skip: int = 0, limit: int = 100):
    """获取聊天列表"""
    chats = await get_user_chats(skip=skip, limit=limit)
    return chats

@router.put("/{chat_id}", response_model=Chat)
async def update_chat_endpoint(chat_id: str, chat: ChatUpdate):
    """更新聊天"""
    updated_chat = await update_chat(chat_id, chat)
    if not updated_chat:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Chat not found"
        )
    return updated_chat

@router.delete("/{chat_id}")
async def delete_chat_endpoint(chat_id: str):
    """删除聊天"""
    result = await delete_chat(chat_id)
    if not result:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Chat not found"
        )
    return {"message": "Chat deleted successfully"}

@router.get("/{chat_id}/messages", response_model=List[Message])
async def read_chat_messages(chat_id: str, skip: int = 0, limit: int = 100):
    """获取聊天消息记录"""
    messages = await get_chat_messages(chat_id, skip=skip, limit=limit)
    return messages

@router.post("/{chat_id}/messages", response_model=Message)
async def create_message(chat_id: str, message: MessageCreate):
    """发送消息"""
    # 验证聊天是否存在
    chat = await get_chat(chat_id)
    if not chat:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Chat not found"
        )
    
    # 创建消息
    # 这里应该调用消息服务创建消息
    # 为简化示例，我们直接返回一个模拟消息
    return Message(
        id="mock_message_id",
        chat_id=chat_id,
        sender_id=message.sender_id,
        content=message.content,
        message_type=message.message_type,
        created_at="2023-01-01T00:00:00",
        is_read=False
    )